package com.android.antelopeapp.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import com.android.antelopeapp.R;
import com.android.antelopeapp.app.UserCustom;
import com.android.antelopeapp.common.GlobalResource;
import com.android.antelopeapp.common.ImageTool;
import com.android.antelopeapp.constant.ApiConfig;
import com.android.antelopeapp.constant.AppConfig;
import com.android.antelopeapp.constant.MsgConfig;
import com.android.antelopeapp.network.UploadUtil;
import com.android.antelopeapp.view.BeautyPic.TagableImage;
import com.google.gson.Gson;
import com.lyhw.model.BeautyPic;
import com.lyhw.model.ImageTag;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by phk on 15-3-31.
 */
public class ShareBpicActivity extends  BaseActivity {
    /**已有标签图片*/
    private TagableImage tagedImg;
    /**内容*/
    private EditText contentEditor;
    /**用于更新ui*/
    private Handler handler;

    public static int INIT_TAGABLEIMAGE=1;
    public static int  UPLOAD_FAILED = 2;

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_bpic_share;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle(null);
        getSupportActionBar().setLogo(null);

        contentEditor = (EditText)this.findViewById(R.id.share_bpic_content);
        /**
         * 发布按键
         * */
        this.findViewById(R.id.share_bpic_publish).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                uploadTagableImage(tagedImg,contentEditor.getText().toString());
            }
        });
        /**
         * 因为在onCreate的时候获取不到tagimage的大小，无法调整tag的位置，所以采用延迟更新的方式。
         * */
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if(msg.what==INIT_TAGABLEIMAGE) {
                    initTagedImage(getIntent());
                }else if(msg.what == UPLOAD_FAILED){
                    toast(MsgConfig.SHARE_BPIC_FAILD);
                }
                return true;
            }
        });
        handler.sendEmptyMessageDelayed(INIT_TAGABLEIMAGE,30);

     }

    /**初始化图片控件*/
    private void initTagedImage(Intent tagsData){
        /**获取图片*/
        tagedImg = (TagableImage) this.findViewById(R.id.tagableimg);
        tagedImg.setImg(GlobalResource.getInstance().getmBitmap(GlobalResource.TAGED_IMG));
        tagedImg.setmInteractModel(TagableImage.NORMAL_MODE);
        /**获取标签*/
        tagedImg.addImgTags(ImageTag.json2tags(tagsData.getData().toString()));
    }
    /**上传图片与标签*/
    private void uploadTagableImage(TagableImage tagableImage,String content) {
        Gson gson = new Gson();
        //create a file to write bitmap data
        final String filename = AppConfig.COMPRESS_PIC_FILE_NAME;
        File f = new File(this.getCacheDir(), filename);
        try {
            f.createNewFile();

            //Convert bitmap to byte array
            ByteArrayOutputStream bos = ImageTool.compressImage(tagableImage.getbmp());
            byte[] bitmapdata = bos.toByteArray();

            //write the bytes in file
            FileOutputStream fos = new FileOutputStream(f);
            fos.write(bitmapdata);
            fos.close();
            BeautyPic bpic = new BeautyPic(content,UserCustom.getInstance().getUserName(),
                    ImageTag.tags2labels(tagableImage.getmTags(),UserCustom.getInstance().getUserName())
            );
            Map<String, String> map = new HashMap<>();
            map.put(ApiConfig.BPIC_BPIC,gson.toJson(bpic));
            UploadUtil.getInstance().setOnUploadProcessListener(new UploadUtil.OnUploadProcessListener() {
                @Override
                public void onUploadDone(int responseCode, String message) {
                    Log.v(TAG, "upload Done ,code:" +responseCode+" msg:"+message);
                    if(responseCode == UploadUtil.UPLOAD_SUCCESS_CODE) {
                        ShareBpicActivity.this.setResult(RESULT_OK);
                        finish();
                    }else{
                        handler.sendEmptyMessageDelayed(UPLOAD_FAILED,0);
                    }
                }

                @Override
                public void onInitUpload() {
                    Log.v(TAG,"initUpload");
                }
            });
            ArrayList<UploadUtil.FileBean> files = new ArrayList<>();
            files.add(new UploadUtil.FileBean(f.getPath(), ApiConfig.TAG_IMAGE_UPLOAD_KEY));
            UploadUtil.getInstance().uploadFile(files, ApiConfig.UPLOAD_BEAUTY_PIC, map);
        } catch (IOException e) {
            Log.getStackTraceString(e);
        }
    }
}
